package com.cuckoo.cuckoo_app2.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.R;
import com.cuckoo.cuckoo_app2.adapters.GenerationAdapter;
import com.cuckoo.cuckoo_app2.adapters.GenerationListAdapter;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.UserApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.VersionControlApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.UserApi;
import com.cuckoo.cuckoo_app2.apiAsync.VersionControlApi;
import com.cuckoo.cuckoo_app2.business.Imp.VersionControlBusinessImp;
import com.cuckoo.cuckoo_app2.business.VersionControlBusiness;
import com.cuckoo.cuckoo_app2.dao.CommissionManagement;
import com.cuckoo.cuckoo_app2.dao.GenerationListItem;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.dao.UserDetails;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.HandlerUtils;
import com.cuckoo.cuckoo_app2.utils.QRCodeUtil;
import com.cuckoo.cuckoo_app2.utils.ScreenUtils;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.card.MaterialCardView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MyInvitationActivity extends AppCompatActivity {

    private Context context;
    private RecyclerView recyclerView;
    private RecyclerView recyclerViewList;
    private List<CommissionManagement> generationItems = new ArrayList<>();
    private List<GenerationListItem> generationListItems = new ArrayList<>();
    private GenerationAdapter adapter;
    private GenerationListAdapter adapterList;
    private Button show_more;
    private int height;
    private UserApi userApi;
    private VersionControlApi versionControlApi;
    private TextView code;
    private MaterialButton btn_copy;
    private MaterialCardView myInvitationList;
    private VersionControlBusiness versionControlBusiness;
    private UserDetails userDetails;
    private Integer pageNo = 1;
    private Integer pageSize = 20;
    private boolean isLoading = false;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_invitation);
        this.context = this;
        this.userApi = new UserApiImp();
        this.versionControlApi = new VersionControlApiImp();
        this.versionControlBusiness = new VersionControlBusinessImp();

        code = findViewById(R.id.code);
        btn_copy = findViewById(R.id.btn_copy);
        btn_copy.setVisibility(android.view.View.GONE);
        myInvitationList = findViewById(R.id.myInvitationList);
        show_more = findViewById(R.id.show_more);

        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        height = displayMetrics.heightPixels; // 屏幕高度（像素）

        // 初始化 RecyclerView
        recyclerView = findViewById(R.id.item_grneration);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 初始化适配器并设置给 RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        adapter = new GenerationAdapter(context, generationItems);
        recyclerView.setAdapter(adapter);

        // item_userlist
        recyclerViewList = findViewById(R.id.item_userlist);
        recyclerViewList.setLayoutManager(new LinearLayoutManager(this));

        adapterList = new GenerationListAdapter(context, generationListItems);
        recyclerViewList.setAdapter(adapterList);

        // 当数据大于20条时才显示
        show_more.setVisibility(View.GONE);
        myInvitationList.setVisibility(View.GONE);

        // 加载数据
        getMyInvitationCode();
        getDataInit();

        // 复制功能
        btn_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HandlerUtils.copyTextToClipboard(context, code.getText().toString());
            }
        });
        // 显示更多
        show_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLoading) {
                    DialogUtils.showToast(context, "正在加载中");
                    return;
                }
                // pageNO + 1 加载下一页
                pageNo += 1;
                getUserList();
            }
        });

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * 生成二维码
     */
    public void createQRCodeWithLogo(String codeContent) {
        Bitmap logoBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        ImageView codeView = findViewById(R.id.codeView);
        QRCodeUtil.createQRCode(codeContent, logoBitmap, codeView, 295, 2);
    }

    /**
     * 获取我的邀请码
     */
    public void getMyInvitationCode() {
        // 检测当前是否可用
        User user = MyApplication.getInstances().getUser();
        if (user == null) {
            DialogUtils.showToast(context, "请先登录");
            return;
        }

        // 生成二维码
        String url = versionControlBusiness.getValueControl("AppDownload");
        createQRCodeWithLogo(url);

        // 获取数据
        userApi.performGetUserByIdAsync(user.getId(), new BaseCallbac<JsonObject>() {

            @Override
            public void onSuccess(JsonObject data) {
                if (!data.get("success").getAsBoolean()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DialogUtils.showToast(context, data.get("message").getAsString());
                        }
                    });
                    return;
                }
                JsonObject result = data.get("result").getAsJsonObject();
                Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
                userDetails = gson.fromJson(result, UserDetails.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        code.setText(userDetails.getInvitCode());
                        btn_copy.setVisibility(View.VISIBLE);
                    }
                });

                getUserList();
            }

            @Override
            public void onFailure(String errorMessage) {

            }
        });

    }


    /**
     * 获取数据
     */
    public void getDataInit() {
        // 获取数据

        versionControlApi.CommissionListAsync(new BaseCallbac<JsonObject>() {

            @Override
            public void onSuccess(JsonObject data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!data.get("success").getAsBoolean()) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    DialogUtils.showToast(context, data.get("message").getAsString());
                                }
                            });
                            return;
                        }
                        CommissionManagement commissionManagement;
                        generationItems = new ArrayList<>();
                        JsonArray result = data.get("result").getAsJsonArray();
                        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
                        for (int i = 0; i < result.size(); i++) {
                            commissionManagement = gson.fromJson(result.get(i).getAsJsonObject(), CommissionManagement.class);
                            generationItems.add(commissionManagement);
                        }
                        adapter.updateData(generationItems);
                    }
                });
            }

            @Override
            public void onFailure(String errorMessage) {

            }
        });
    }

    /**
     * 获取用户列表
     */
    public void getUserList() {
        // 获取数据
        HashMap<String, String> params = new HashMap<>();
        params.put("pageNo", pageNo.toString());
        params.put("pageSize", pageSize.toString());
        params.put("registerCode", userDetails.getInvitCode());

        isLoading = true;
        userApi.performGetUserListAsync(params, new BaseCallbac<JsonObject>() {
            @Override
            public void onSuccess(JsonObject data) {
                isLoading = false;
                // 视图
                runOnUiThread(() -> {
                    if (!data.get("success").getAsBoolean()) {
                        DialogUtils.showToast(context, data.get("message").getAsString());
                        return;
                    }
                    JsonObject result = data.get("result").getAsJsonObject();
                    int total = result.get("total").getAsInt();
                    if (total <= 0) {
                        return;
                    }
                    myInvitationList.setVisibility(View.VISIBLE);

                    String dateStr;
                    JsonObject re;
                    UserDetails ud;
                    GenerationListItem glt;
                    JsonArray records = result.get("records").getAsJsonArray();
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
                    for (int i = 0; i < records.size(); i++) {
                        re = records.get(i).getAsJsonObject();
                        ud = gson.fromJson(re, UserDetails.class);
                        dateStr = sdf.format(ud.getCreateTime());
                        glt = new GenerationListItem();
                        glt.setAccount(ud.getUserName());
                        glt.setIsVip(ud.getIsVip());
                        glt.setTime(dateStr);
                        generationListItems.add(glt);
                    }
                    ScreenUtils.showMore(context, recyclerViewList, generationListItems.size(), 40);
                    // 是否显示更多
                    int showMore = ScreenUtils.isShowMore(total, pageSize, pageNo);
                    show_more.setVisibility(showMore);

                    adapterList.updateData(generationListItems);
                });
            }

            @Override
            public void onFailure(String errorMessage) {
                isLoading = false;
            }
        });
    }
}
